//
//  MainIndustrialControlController.m
//  ERP
//
//  Created by QA on 16/4/25.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MainIndustrialControlController.h"
#import "GETableView.h"
#import "Charts-Swift.h"

#import "NSDictionary+DataFormat.h"
#import "TOWebViewController.h"
#import "RTSpinKitView.h"
#import "HYBLoopScrollView.h"
#import "PopoverView.h"
#import "GEObjectButton.h"
#import "GEObjectValueTableViewCell.h"
#import "LevelGageController.h"

#import "MJRefresh.h"
#import "GEDateFromatter.h"

#import "WebViewController.h"
#import "GEPushViewControllerHelper.h"
#import "GEProgressBarTableViewCell.h"
#import "LevelGageItemView.h"

#import "DateTimeFormat.h"
#import "ModuleAuthorityEntity+CoreDataClass.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "UIView+AssistView.h"
#import "NSArray+Format.h"
#import "XTTapGestureRecognizer.h"

#import "MainIndustrialSudokuCell.h"
#import "MainIndustrialControlCell.h"
#import "UINavigationBar+Awesome.h"
#import "UIImage+Color.h"
#import "YFViewPager.h"

@interface MainIndustrialControlController ()<UIGestureRecognizerDelegate>

@property (nonatomic,strong) IBOutlet GETableView *tableView;

@property (nonatomic, strong) NSArray *moduleArray;
@property (nonatomic, strong) NSMutableArray *menuArray;

@end

@implementation MainIndustrialControlController

- (id)init
{
    self = [super init];
    if (self) {
        //添加菜单权限获取注册
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:GetUserBasicInfoServiceKey object:nil];
    }
    return self;
}

- (void)dealloc
{
    //移除菜单权限获取注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.tableView.contentInset = UIEdgeInsetsMake(-1, 0, 0, 0);
    
    //添加进度条
    RTSpinKitView *spinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleFadingCircleAlt];
    spinner.center = CGPointMake(SuperWidth / 2, CGRectGetMidY(self.tableView.frame));
    [spinner startAnimating];
    [self.tableView addSubview:spinner];
    
    //添加下拉加载数据
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    UILongPressGestureRecognizer *ge=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cancelScroll:)];
    [ge setDelegate:self];
    [ge setMinimumPressDuration:0.1];//这里为了让他在tableview还是能够进行整个scroll的拖动所以用了0.1给用户一个快速拖动
    [self.tableView addGestureRecognizer:ge];
    
    //数据查询
    [self getSqliteData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    
    //去除黑色阴影线
    UIImage *image = [UIImage imageWithColor:[UIColor colorWithWhite:0.9 alpha:1] size:CGSizeMake(SuperWidth, 0.5)];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6){
        [self.navigationController.navigationBar setShadowImage:image];
    }
    
    //状态栏字体改变
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColorDispose colorWithHexString:@"#333333"], NSForegroundColorAttributeName,
                                                                     [UIFont systemFontOfSize:18.0], NSFontAttributeName, nil]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 开始进入刷新状态

- (void)headerRereshing
{
    // 延迟2秒执行：
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // code to be executed on the main queue after delay
        [self.tableView headerEndRefreshing];
    });
    
    [self.tableView removeAllSaveCell];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark - NSNotificationCenter

-(void)updateMenuAuthorityService:(NSNotification *)notification
{
    //获取菜单权限列表
    if ([[notification name] isEqualToString:GetUserBasicInfoServiceKey]){
        [self getSqliteData];
    }
}

#pragma mark  获取页面功能权限

- (void)getSqliteData
{
    //获取主模块
    NSPredicate *predicateMain = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", @0, @3];
    ModuleAuthorityEntity *mainEntity = [ModuleAuthorityEntity MR_findFirstWithPredicate:predicateMain sortedBy:@"order" ascending:YES];
    
    //获取主菜单
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", mainEntity.id, @3];
    NSArray *moduleArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:predicate];
    self.moduleArray = moduleArray;
    
    //获取菜单功能模块
    self.menuArray = [NSMutableArray array];
    for (ModuleAuthorityEntity *entity in moduleArray) {
        NSPredicate *menuPredicat = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", entity.id, @3];
        NSArray *menuArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:menuPredicat];
        [self.menuArray addObject:menuArray];
    }
    
    //页面数据配置
    [self.tableView reloadData];
    
    //移除进度条
    if(moduleArray.count <= 0){
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView showPromptViewText:@"暂无模块" rect:CGRectMake(0, 0, SuperWidth, SuperHeight - 128) blcok:nil];
    }
    
    //异常进度条
    NSArray *viewArray = self.tableView.subviews;
    for (id view in viewArray) {
        if ([view isKindOfClass:[RTSpinKitView class]]) {
            RTSpinKitView *mSpinKitView = view;
            [mSpinKitView removeFromSuperview];
        }
    }
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 10;
    return 0.000001f;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.moduleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [self.menuArray objectAtIndex:indexPath.section];
    ModuleAuthorityEntity *entity = [self.moduleArray objectAtIndex:indexPath.section];
    
    /*****料位计*****/
    if(entity.module.integerValue == 2){
        GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (progressBarCell == nil) {
            NSString *identifierBar = [NSString stringWithFormat:@"GEProgressBarTableViewCell%ld",(long)indexPath.section];
            progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar height:315];
            progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
        }
        
        //判读有无数据，有数据就加载页面
        if(progressBarCell.objectValue){
            NSString *keyValue = [NSString stringWithFormat:@"gkkb-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
            GEObjectValueTableViewCell *cell  = [self.tableView getCellViewKey:keyValue];
            if (cell == nil) {
                cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.objectValue = progressBarCell.objectValue;
                [self materialChargeInCell:cell indexPath:indexPath];
                [self.tableView setCellView:cell key:keyValue];
            }
            return cell;
        }
        
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"ZNYJ-LWJTC-TB" parameter:nil StationID:0 interfaceType:1 index:indexPath.section];
        return progressBarCell;
    }
    
    /*****工控看板*****/
    if(entity.module.integerValue == 1){
        GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (progressBarCell == nil) {
            NSString *identifierBar = [NSString stringWithFormat:@"GEProgressBarTableViewCell%ld",(long)indexPath.section];
            progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
            progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
        }
        
        //判读有无数据，有数据就加载页面
        if(progressBarCell.objectValue){
            NSString *keyValue = [NSString stringWithFormat:@"gkkb-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
            MainIndustrialControlCell *cell = [self.tableView getCellViewKey:keyValue];
            if (!cell) {
                NSArray *valueArray = [progressBarCell.objectValue objectAtIndexFormat:0];
                //大于4个站，采用多站点显示方式
                if(valueArray.count<=4){
                    cell = [[MainIndustrialControlCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue index:0];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    [self capacityAnalysis:cell data:progressBarCell.objectValue];
                    [self drawStationView:cell data:progressBarCell.objectValue];
                } else {
                    cell = [[MainIndustrialControlCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue index:1];
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    [self capacityMuliteAnalysis:cell data:progressBarCell.objectValue];
                }
                [self.tableView setCellView:cell key:keyValue];
            }
            return cell;
        }
        
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"ZNYJ_ZNGK_ZJCN" parameter:nil StationID:0 interfaceType:1 index:indexPath.section];
        return progressBarCell;
    }
    
    /*****工控相关功能*****/
    if(entity.module.integerValue == 3){
        NSString *keyValue = [NSString stringWithFormat:@"ad-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
        MainIndustrialSudokuCell *cell = [tableView dequeueReusableCellWithIdentifier:keyValue];
        if (!cell) {
            cell = [[MainIndustrialSudokuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            [cell setMenuArray:array navigation:self.navigationController];
        }
        return cell;
    }
    
    //无数据页面
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark
#pragma mark - 料位计

- (void)materialChargeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *array = cell.objectValue;
    NSArray *scLineData = [array objectAtIndex:0];
    
    NSMutableArray *views = [NSMutableArray array];
    NSMutableArray *titleArray = [NSMutableArray array];
    for(int i=0; i<scLineData.count; i++){
        NSDictionary *dictionary = [scLineData objectAtIndex:i];
        [titleArray addObject:[dictionary objectFormatStringForKey:@"生产线"]];
        
        NSArray *data = [array objectAtIndex:i+1];
        UIView *view = [[LevelGageItemView alloc] initWithData:data];
        [views addObject:view];
    }
    
    //绘制主体页面
    YFViewPager *_viewPager = [[YFViewPager alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 270)
                                                          titles:titleArray icons:nil selectedIcons:nil views:views];
    _viewPager.tabSelectedArrowBgColor = ThemeColorBlue;
    _viewPager.tabSelectedTitleColor = ThemeColorBlue;
    _viewPager.tabTitleColor = [UIColor colorWithWhite:0.1 alpha:0.75];
    _viewPager.showBottomLineHeight = 0.5;
    _viewPager.vLineWidth = 0.5;
    //_viewPager.enabledScroll = NO;
    [cell.contentView addSubview:_viewPager];
    
    //绘制页面跳转按钮
    [self drawJumpViewCell:cell];
    
}

- (void)drawJumpViewCell:(GEObjectValueTableViewCell*)cell {
    NSArray *array = cell.objectValue;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 270, SuperWidth, 38)];
    view.tag = 1001;
    [cell.contentView addSubview:view];
    
    XTTapGestureRecognizer *tapGesturRecognizer=[[XTTapGestureRecognizer alloc]initWithTarget:self action:@selector(ItemAction:)];
    tapGesturRecognizer.delegate = self;
    [view addGestureRecognizer:tapGesturRecognizer];
    tapGesturRecognizer.tagObject = array;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.88 alpha:1];
    [view addSubview:lineView];
    
    //绘制按钮
    UIImageView *iconImage = [[UIImageView alloc] initWithFrame:CGRectMake(8, 6, 32, 32)];
    iconImage.image = [UIImage imageNamed:@"report_all_icon"];
    [view addSubview:iconImage];
    
    UILabel *titleView = [[UILabel alloc] initWithFrame:CGRectMake(45, 8, SuperWidth-80, 30)];
    titleView.text = @"料位计实时情况";
    titleView.font = [UIFont systemFontOfSize:15];
    titleView.textColor = [UIColor colorWithWhite:0.3 alpha:1];
    [view addSubview:titleView];
    
    UILabel *describeView = [[UILabel alloc] initWithFrame:CGRectMake(SuperWidth-50, 13, 30, 20)];
    describeView.text = @"详情";
    describeView.font = [UIFont systemFontOfSize:13];
    describeView.textColor = ThemeColorBlue;
    [view addSubview:describeView];
    
    UIImageView *describeImage = [[UIImageView alloc] initWithFrame:CGRectMake(SuperWidth-20, 16, 13, 13)];
    describeImage.image = [UIImage imageNamed:@"report_modle_right"];
    [view addSubview:describeImage];
}

- (void)ItemAction:(XTTapGestureRecognizer*)sender {
    NSArray *array = sender.tagObject;
    
    LevelGageController *viewController = [[LevelGageController alloc] initWithValue:array];
    [self.navigationController pushViewController:viewController animated:YES];

}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    //防止影响其他空间滑动
    if (touch.view.tag == 1001 && [gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]){
        return YES;
    }
    return NO;
}

#pragma mark
#pragma mark - 工控机生产方量

- (void)capacityAnalysis:(MainIndustrialControlCell *)cell data:(NSArray*)array
{
    NSInteger width = (SuperWidth == 375) ? SuperWidth/3*2 : SuperWidth/3*2 - 10;
    
    NSString *runTime = [GEDateFromatter stringFromDate:[NSDate date]];
    [cell.runTimeLabel setText:[NSString stringWithFormat:@"数据更新于%@",runTime]];
    
    //数据处理
    CGFloat sczl = 0;
    for(NSArray *childArray in array){
        for(int j =0;j<childArray.count;j++){
            NSDictionary *dic = [childArray objectAtIndex:j];
            sczl += [dic objectFormatFloatForKey:@"生产方量" retain:1 except:1];
        }
    }
    
    //绘制图表
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(116, 32, width, 200)];
    _chartView.usePercentValuesEnabled = YES;
    //_chartView.centerTextFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:12.f];
    _chartView.holeRadiusPercent = 0.52f;
    _chartView.transparentCircleRadiusPercent = 0.56f;
//    _chartView.descriptionText = @"";
    _chartView.drawCenterTextEnabled = YES;
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.f;
    _chartView.rotationEnabled = YES;
    _chartView.userInteractionEnabled = NO;
    _chartView.centerText = [NSString stringWithFormat:@"总产能\n%0.2f方",sczl];
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentTop;
    l.orientation = ChartLegendOrientationVertical;
    l.xEntrySpace = 5.f;
    //l.yEntrySpace = 50.f;
    
    _chartView.data = [self setData:array];
    [_chartView highlightValues:nil];
    [_chartView animateWithXAxisDuration:1.5 yAxisDuration:1.5 easingOption:ChartEasingOptionEaseOutBack];
    [cell.contentView addSubview:_chartView];
}

- (PieChartData*)setData:(NSArray*)array
{
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    
    //数据处理
    for(NSArray *childArray in array){
        for(int j =0;j<childArray.count;j++){
            NSDictionary *dic = [childArray objectAtIndex:j];
            NSString *name = [dic objectFormatStringForKey:@"站点"];
            CGFloat scflValue = [dic objectFormatFloatForKey:@"生产方量" retain:1 except:1];
            [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:scflValue label:name]];
        }
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@""];
    dataSet.sliceSpace = 2.f;
    [dataSet setDrawValuesEnabled:NO];
    
    // add a lot of colors -- ThemeColorLigthBlue
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorGreen];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    [colors addObject:[UIColor colorWithRed:202/255.f green:202/255.f blue:202/255.f alpha:1.f]];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"%";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:[UIColor colorWithWhite:1 alpha:0]];
    
    return data;
}

- (void)drawStationView:(MainIndustrialControlCell *)cell data:(NSArray*)array
{
    //数据处理
    for(NSArray *childArray in array){
        NSInteger count = childArray.count;
        cell.scrollView.contentSize = CGSizeMake(116, 50.5*count);
        cell.scrollView.userInteractionEnabled = YES;
        cell.scrollView.scrollEnabled = YES;
        
        for(int j =0;j<count;j++){
            NSDictionary *dic = [childArray objectAtIndex:j];
            NSString *name = [dic objectFormatStringForKey:@"站点"];
            NSString *scflValue = [dic objectFormatFloatStringForKey:@"生产方量" retain:2 format:@"%@方"];
            
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, j*50.5, 116, 50.5)];
            [cell.scrollView addSubview:view];
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(4, 10, 30, 30)];
            imageView.image = [UIImage imageNamed:@"zd_g"];
            [view addSubview:imageView];
            
            UILabel *stationLabel = [[UILabel alloc] initWithFrame:CGRectMake(36, 6, 90, 21)];
            stationLabel.text = name;
            stationLabel.font = [UIFont systemFontOfSize:13];
            stationLabel.textColor = [UIColor darkGrayColor];
            [view addSubview:stationLabel];
            
            UILabel *flLabel = [[UILabel alloc] initWithFrame:CGRectMake(36, 26, 90, 21)];
            flLabel.text = scflValue;
            flLabel.textColor = [UIColor darkGrayColor];
            flLabel.font = [UIFont systemFontOfSize:14];
            [view addSubview:flLabel];
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, 116, 0.5)];
            lineView.backgroundColor = [UIColor colorWithRed:221/255.0 green:221/255.0  blue:221/255.0  alpha:1];
            [view addSubview:lineView];
        }
    }
    
}


#pragma mark
#pragma mark - 工控机生产方量（多站点情况）

- (void)capacityMuliteAnalysis:(MainIndustrialControlCell *)cell data:(NSArray*)array
{
    NSString *runTime = [GEDateFromatter stringFromDate:[NSDate date]];
    [cell.runTimeLabel setText:[NSString stringWithFormat:@"数据更新于%@",runTime]];
    
    //数据处理
    CGFloat sczl = 0;
    for(NSArray *childArray in array){
        for(int j =0;j<childArray.count;j++){
            NSDictionary *dic = [childArray objectAtIndex:j];
            sczl += [dic objectFormatFloatForKey:@"生产方量" retain:2 except:1];
        }
    }
    
    PieChartView *_chartView = [[PieChartView alloc] initWithFrame:CGRectMake(0, 32, SuperWidth, 200)];
    _chartView.holeRadiusPercent = 0.52;
    _chartView.transparentCircleRadiusPercent = 0.53;
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"";
    _chartView.drawCenterTextEnabled = YES;
    [_chartView setExtraOffsetsWithLeft:0 top:0 right:10.f bottom:0];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSString *xhzl = [NSString stringWithFormat:@"%0.1f方",sczl];
    NSString *text = [NSString stringWithFormat:@"总产能\n%@",xhzl];
    NSMutableAttributedString *centerText = [[NSMutableAttributedString alloc] initWithString:text];
    [centerText setAttributes:@{
                                NSFontAttributeName:[UIFont boldSystemFontOfSize:13.0f],
                                NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName:[UIColor grayColor]
                                } range:NSMakeRange(0, text.length)];
    _chartView.centerAttributedText = centerText;
    
    _chartView.drawHoleEnabled = YES;
    _chartView.rotationAngle = 0.0;
    _chartView.rotationEnabled = YES;
    _chartView.highlightPerTapEnabled = YES;

    _chartView.drawEntryLabelsEnabled = NO;
    _chartView.usePercentValuesEnabled = NO;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentRight;
    l.verticalAlignment = ChartLegendVerticalAlignmentCenter;
    l.orientation = ChartLegendOrientationVertical;
    l.font = [UIFont systemFontOfSize:10];
    l.yEntrySpace = 3;
    l.yOffset = -15;
    l.xOffset = 8;

    
    [self setMaterialConsumeData:_chartView data:array];
    [_chartView animateWithXAxisDuration:1.4 yAxisDuration:1.4 easingOption:ChartEasingOptionEaseOutBack];
    [cell.contentView addSubview:_chartView];
}

- (void)setMaterialConsumeData:(PieChartView *)_chartView data:(NSArray*)valueArray
{
    NSArray *array = [valueArray objectAtIndexFormat:0];
    
    NSMutableArray *yVals1 = [[NSMutableArray alloc] init];
    for (int i = 0; i < array.count; i++){
        NSDictionary *mDictionary = [array objectAtIndex:i];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"生产方量"];
        CGFloat numberValue = [mDictionary objectFormatFloatForKey:@"生产方量" retain:2 except:1];
        NSString *titleValue = [mDictionary objectFormatStringForKey:@"站点" defaults:@"未知"];
        NSString *valueNameStr = [NSString stringWithFormat:@"%@  %0.2f方",titleValue,numberValue];
        [yVals1 addObject:[[PieChartDataEntry alloc] initWithValue:value label:valueNameStr]];
    }
    
    PieChartDataSet *dataSet = [[PieChartDataSet alloc] initWithValues:yVals1 label:@"生产站点"];
    dataSet.sliceSpace = 2.0;
    dataSet.drawValuesEnabled = NO;
    //dataSet.drawIconsEnabled = NO;
    
    // add a lot of colors
    NSMutableArray *colors = [[NSMutableArray alloc] init];
    [colors addObject:ThemeColorGreen];
    [colors addObject:ThemeColorLigthBlue];
    [colors addObjectsFromArray:ChartColorTemplates.vordiplom];
    [colors addObjectsFromArray:ChartColorTemplates.joyful];
    [colors addObjectsFromArray:ChartColorTemplates.colorful];
    [colors addObjectsFromArray:ChartColorTemplates.liberty];
    [colors addObjectsFromArray:ChartColorTemplates.pastel];
    dataSet.colors = colors;
    
    NSNumberFormatter *pFormatter = [[NSNumberFormatter alloc] init];
    pFormatter.numberStyle = NSNumberFormatterPercentStyle;
    pFormatter.maximumFractionDigits = 1;
    pFormatter.multiplier = @1.f;
    pFormatter.percentSymbol = @"T";
    
    PieChartData *data = [[PieChartData alloc] initWithDataSet:dataSet];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:pFormatter]];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:11.f]];
    [data setValueTextColor:UIColor.whiteColor];
    
    _chartView.data = data;
    [_chartView highlightValues:nil];
}

#pragma mark
#pragma mark -

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    //切记这个代理必须要设置、因为scroll的拖动说白了也是一个gesture、为了流畅性必须要两个触碰事件同时触发
    return YES;
}
-(void)cancelScroll:(UIGestureRecognizer*)gesture
{
    //这里就是让背景的拖动定死这样就不冲突了
    if ([gesture state]==UIGestureRecognizerStateBegan) {
        [self.tableView setScrollEnabled:NO];
    }
    
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //拖动完再恢复
    [self.tableView setScrollEnabled:YES];
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ModuleAuthorityEntity *entity = [self.moduleArray objectAtIndex:indexPath.section];
    if(entity.module.integerValue == 1){
        return 226;
    }else if(entity.module.integerValue == 2){
        return 315;
    } else if(entity.module.integerValue == 3){
        NSArray *array = [self.menuArray objectAtIndex:indexPath.section];
        return [MainIndustrialSudokuCell getHeightItemCount:array.count];
    }
    return 0;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
    //[tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSArray *moduleArray = [self.menuArray objectAtIndex:indexPath.section];
//    if(indexPath.row >= moduleArray.count) return;
//    
//    ModuleAuthorityEntity *entity = [moduleArray objectAtIndex:indexPath.row];
//    if(entity.codeType.integerValue == 1){
//        //网页模式
//        WebPushParameterModel *model = [[WebPushParameterModel alloc] init];
//        model.URL = entity.webCode;
//        model.Title = entity.title;
//        model.CodeType = CodeTypeWeb;
//        
//        WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:model];
//        [self.navigationController pushViewController:viewController animated:YES];
//    } else {
//        //原生APP模式
//        [GEPushViewControllerHelper pushViewControllerHomePageCode:entity.nativeCode navigation:self.navigationController];
//    }
//}

@end
